package com.yuanbuluo.sendsms

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Telephony
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {

    private val SMS_PERMISSION_CODE = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 请求忽略电池优化
        disableBatteryOptimizations()


        // 动态请求短信权限
        if (!checkSmsPermissions()) {
            requestSmsPermissions()
        }

        // 启动后台服务按钮
        val startButton = findViewById<Button>(R.id.startButton)
        startButton.setOnClickListener {
            if (checkSmsPermissions()) {
                val intent = Intent(this, SmsService::class.java)
                startService(intent) // 启动服务
                Toast.makeText(this, "短信后台服务已启动", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "未授予短信权限", Toast.LENGTH_SHORT).show()
                requestSmsPermissions()
            }
        }
    }

    private fun disableBatteryOptimizations() {
        val intent = Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
        intent.data = Uri.parse("package:$packageName")
        startActivity(intent)
    }

    /**
     * 检查是否已授予短信权限
     */
    private fun checkSmsPermissions(): Boolean {
        val permissions = arrayOf(
            android.Manifest.permission.SEND_SMS,
            android.Manifest.permission.READ_SMS,
            android.Manifest.permission.RECEIVE_SMS
        )
        return permissions.all {
            ContextCompat.checkSelfPermission(this, it) == android.content.pm.PackageManager.PERMISSION_GRANTED
        }
    }

    /**
     * 动态请求短信权限
     */
    private fun requestSmsPermissions() {
        val permissions = arrayOf(
            android.Manifest.permission.SEND_SMS,
            android.Manifest.permission.READ_SMS,
            android.Manifest.permission.RECEIVE_SMS
        )
        ActivityCompat.requestPermissions(this, permissions, SMS_PERMISSION_CODE)
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == SMS_PERMISSION_CODE) {
            if (grantResults.isNotEmpty() && grantResults.all { it == android.content.pm.PackageManager.PERMISSION_GRANTED }) {
                Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "权限被拒绝，无法发送短信", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
